<template>
  <view
    class="login"
    v-if="showPage"
  >
    <!-- 状态栏占位 -->
    <!-- <uni-nav-bar backgroundColor="#ffffff" leftText="" :statusBar="true" :shadow="false" :fixed="true" color="#2e2e2e" /> -->
    <view class="avatar">
      <image
        class="avatarimg"
        src="@/static/img/logo.png"
        mode="widthFix"
      ></image>
    </view>
    <view class="loginTitle">
      欢迎登录游到彼岸
    </view>
    <view class="loginmethod">
      <!-- #ifdef MP-WEIXIN -->
      <button
        class="loginmethodT"
        @click="getUserInfo"
      >用户一键登录</button>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <view
        class="loginmethodT"
        @tap="weixinlogin"
      >用户一键登录</view>
      <!-- #endif -->
      <!-- <view class="loginmethodM">手机号码登录/注册</view> -->
    </view>
    <view class="loginmethod">
      <view
        class="loginmethodT1"
        @click="goHome()"
      >游客登录</view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <get-number v-if="login_status===1" />
    <!-- #endif -->
    <!-- #ifdef H5 -->
    <!-- <getPhoneNumberGZH v-if="login_status===1" /> -->
    <!-- #endif -->
    <!-- 登录注册说明 -->
    <!-- <view class="modelmiddlefoot">
				<label>
					<checkbox class="modelmiddlefootcheckbox" :checked="checked" @click="checked=!checked" />
				</label>
				登录代表您已同意济南便民港平台
				<text class="modelmiddlefootagreement" @click="goVHtml('LOGIN')">《服务协议》</text>
		</view> -->
  </view>
</template>

<script>
// import getPhoneNumberGZH from './component/getPhoneNumberGZH.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'login',
  components: {
    // getPhoneNumberGZH
  },
  data() {
    return {
      imgUrl: this.$apiFun.imgUrl,
      host: this.$apiFun.host,
      checked: false,
      loginCode: '', //小程序login 获取的code
      winUrl: '',
      showPage: true,
    }
  },
  computed: {
    //login_status 0 未登录 、1临时微信登录 2已登录
    ...mapGetters(['login_status', 'configObj', 'userInfo', 'saleCode']),
  },
  onLoad(option) {
    // #ifdef MP-WEIXIN
    if (option && option.code) {
      this.showPage = false
      uni.showLoading({
        title: '登陆中...',
      })
      this.gzhLoginCallBack(option.code)
    }
    // #endif
  },
  mounted() {
    // #ifdef H5
    console.log('option1-----', this.getUrlCode())
    if (this.getUrlCode().code) {
      this.loginCallBack()
      this.showPage = false
      uni.showLoading({
        title: '登陆中...',
      })
    }
    // #endif
  },
  methods: {
    xcxlogin() {
      return new Promise((resove, reject) => {
        uni.login({
          provider: 'weixin',
          success: function (res) {
            console.log('小程序code-------', res.code)
            return resove(res.code)
          },
          fail: function (err) {
            reject()
            console.log('----小程序err----->', err)
          },
        })
      })
    },
    goVHtml(id) {
      // uni.navigateTo({
      // 	url:'/webView/vHtml?id='+id+'&title='+'用户协议'
      // })
    },
    // 微信公众号授权登录
    weixinlogin() {
      let url =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        this.$apiFun.APPID +
        '&redirect_uri=' +
        this.$apiFun.ToREDIRECT_URI +
        '&response_type=code&scope=' +
        this.$apiFun.SCOPE +
        '&state=' +
        this.$apiFun.STATE +
        '#wechat_redirect'
      window.location.href = url
    },
    // 截取url中的code方法
    getUrlCode() {
      var url = location.href
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf('?') != -1) {
        var str = url.substr(url.indexOf('?') + 1)
        var strs = str.split('&')
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]
        }
      }
      return theRequest
    },
    gzhLoginCallBack(code) {
      var that = this
      var param = { code: code, userId: this.userInfo.id }
      this.$apiFun.getApi(
        this.$api.bindWxAndGzhUserApi,
        param,
        function (res) {
          const { code, data } = res
          if (code == 200) {
            uni.hideLoading()
            that.wxLoginUserInfoApiFun().then(() => {
              that.loginSuccess()
            })
          }
        },
        function (err) {}
      )
    },
    loginSuccess() {
      uni.hideLoading()
      uni.showToast({
        title: '登陆成功!',
        icon: 'none',
      })
      if (uni.getStorageSync('beforePage')) {
        uni.reLaunch({
          url: uni.getStorageSync('beforePage'),
          success() {
            uni.removeStorageSync('beforePage')
          },
        })
      } else {
        uni.reLaunch({
          url: '/pages/uni_Home',
        })
      }
    },
    loginCallBack() {
      var that = this
      var param = { code: this.getUrlCode().code }
      this.$apiFun.getApi(
        this.$api.callBackApi,
        param,
        function (res) {
          const { code, data } = res
          if (code == 200) {
            uni.setStorage({
              key: 'localtokn',
              data: data.token,
            })
            that.$store.dispatch('setLoginStatus', 1)
            uni.showToast({
              title: '登陆成功!',
              icon: 'none',
            })
            that.wxLoginUserInfoApiFun().then(() => {
              // h5 跳转
              window.location.href = 'https://web.jngkxx.top/H5/Yizhantong/#/'
            })
          }
        },
        function (err) {}
      )
    },
    // 个人中心接口
    wxLoginUserInfoApiFun() {
      var that = this
      const param = {}
      return new Promise((resove, reject) => {
        that.$apiFun.getApi(
          that.$api.wxLoginUserInfoApi,
          param,
          function (res) {
            const { code, data } = res
            if (code == 200) {
              that.$store.dispatch('setUserInfos', data)
              resove(data)
            }
          },
          function (err) {}
        )
      })
    },
    //微信小程序授权登录
    getUserInfo() {
      let that = this
      // if(!this.checkedFun()) return
      uni.showLoading({
        title: '登录中',
      })
      this.getSetting().then(function (isAuth) {
        console.log('是否已经授权', isAuth)
        if (isAuth) {
          // 获取用户信息
          uni.getUserProfile({
            desc: '用于完善用户资料',
            success: function (infoRes) {
              // 获取小程序opendid
              that
                .xcxlogin()
                .then((code) => {
                  that.getUserLogin(code, infoRes)
                })
                .catch(() => {
                  uni.hideLoading()
                })
            },
            fail: function (err) {
              uni.hideLoading()
            },
          })
        } else {
          uni.showToast({
            title: '授权失败，请确认授权已开启',
            mask: true,
            icon: 'none',
          })
        }
      })
    },
    // 游客登录
    goHome() {
      this.$store.dispatch('setLoginStatus', null)
      uni.reLaunch({
        url: '/pages/uni_Home',
      })
    },
    // 登录接口
    async getUserLogin(code, infoRes) {
      var that = this
      const param = {
        code: code,
        rawData: infoRes.rawData,
        signature: infoRes.signature,
        encryptedData: infoRes.encryptedData,
        iv: infoRes.iv,
        saleCode: this.saleCode || '',
      }
      // console.log('param---------',param)
      // return
      const data = await that.$apiFun.postApi(this.$api.userLoginApi, param)
      console.log('data----------', data)
      console.log('小程序登录授权完毕 准备登录-且验证公众号opendid')
      uni.hideLoading()
      that.$store.dispatch('setUserInfos', data)
      uni.setStorage({
        key: 'localtokn',
        data: data.token,
      })
      // 设置登录状态
      if (data.phone) {
        that.$store.dispatch('setLoginStatus', 2)
      } else {
        that.$store.dispatch('setLoginStatus', 1)
      }
      that.loginSuccess()
    },
    // 勾选框 按钮
    checkedFun() {
      if (!this.checked) {
        uni.showToast({
          icon: 'none',
          title: '请阅读并勾选《服务协议》',
        })
        return false
      } else {
        return true
      }
    },
    //获取用户的当前设置
    getSetting() {
      return new Promise(function (resolve, reject) {
        uni.getSetting({
          success: function (res) {
            if (res.authSetting['scope.userInfo']) {
              console.log('存在')
              resolve(true)
            } else {
              console.log('不存在')
              resolve(false)
            }
          },
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    // 导航返回
    BackLeft() {
      uni.navigateBack()
    },
  },
  onHide() {
    // 页面一旦退出 立刻清除路由的缓存
    uni.removeStorageSync('beforePage')
  },
}
</script>
<style>
page {
  height: 100%;
  background: #000000;
  color: white;
}
</style>
<style scoped lang="less">
.login {
  width: 100%;
  .avatar {
    width: 200rpx;
    height: 200rpx;
    padding-top: 135rpx;
    margin: 0 auto;
    .avatarimg {
      width: 200rpx;
      height: 200rpx;
      border-radius: 6rpx;
    }
  }
  .loginTitle {
    width: 100%;
    text-align: center;
    margin-top: 30rpx;
    font-size: 33rpx;
    border-radius: 10rpx;
  }
  .loginmethod {
    padding: 0 45rpx;
    box-sizing: border-box;
    text-align: center;
    width: 100%;
    .loginmethodT {
      width: 100%;
      text-align: center;
      font-size: 26rpx;
      height: 80rpx;
      background-color: #0ab71f;
      border-radius: 10rpx;
      color: #ffffff;
      line-height: 80rpx;
      margin-top: 200rpx;
      border: none !important;
      padding: 0 !important;
    }
    .loginmethodT1 {
      margin-top: 20rpx;
      width: 100%;
      text-align: center;
      font-size: 26rpx;
      color: #ffffff;
    }
    .loginmethodM {
      font-size: 24rpx;
      color: #ffffff;
      margin-top: 50rpx;
    }
  }
  .modelmiddlefoot {
    padding: 0 30rpx;
    font-size: 22rpx;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 60rpx;
    .modelmiddlefootagreement {
      color: #4089aa;
    }
  }
}
</style>
